#!/usr/bin/python 
# @Time  : 2021/5/18 21:27
# @Author: LOUIE
# @Desc  : api封装，目的是为了之后集成测试平台提供接口
from utils import loader
from core.response import HttpResponse
from core.session import HttpRequest


def run_test(config, variable, tests_dict):
    # 对获取的HTTP请求数据进行加工
    url = loader.build_url(config, tests_dict.get('url'), variable)
    method = loader.build_method(tests_dict.get('method'))
    request = loader.build_request(tests_dict.get('request'), variable)
    validator = loader.build_validator(tests_dict.get('validate'), variable)
    # 发起HTTP请求
    response = HttpRequest().send_request(method, url, tests_dict.get('name'), **request)
    # 对响应内容进行处理
    resp = HttpResponse(response)
    # 对结果进行断言
    if validator:
        resp.validate(validator)
    extractor = tests_dict.get('extract')
    if extractor:
        extract_variable = resp.extract_value(extractor)
        variable.update(extract_variable)


def run_testcase(filepath):
    testcase = loader.load_yaml(filepath)
    config = testcase.get("config", {})
    variable = loader.load_env_variables(config)
    teststeps = testcase.get("steps", [])
    for test_dict in teststeps:
        run_test(config, variable, test_dict)


if __name__ == '__main__':
    run_testcase('address.yaml')